#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
#include <condition_variable>

std::mutex myMutex;
std::condition_variable cv;
bool isDataReady = false;

// 等待者，消费者
void waitForData() {
    std::cout << "wait for data ..." << std::endl;
    std::unique_lock<std::mutex> lock(myMutex);
    // 为什么用unique_lock,cv.wait需要能暂时释放和获取锁的能力
    cv.wait(lock, [] { return isDataReady; });  // 等待条件变量满足

    for (size_t i = 0; i < 3; i++)
    {
        std::cout << "i : " << i << std::endl;
    }
    // 处理数据
}


// 通知方，生产者
void setDataReady() {
    std::lock_guard<std::mutex> lock(myMutex);
    std::this_thread::sleep_for(std::chrono::seconds(3));
    isDataReady = true;
    cv.notify_one();  // 发送信号，通知等待的线程
}

int main() {
    std::thread t1(waitForData);
    std::thread t2(setDataReady);

    t1.join();

    t2.join();

    return 0;
}